package mm.chenchen.modules.sys.service.impl;

import mm.chenchen.common.utils.DateUtils;
import mm.chenchen.db.annotation.DataSource;
import mm.chenchen.modules.sys.dao.MysqlBackupDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.*;

@Service
////@DataSource("爬虫资源库")
public class MysqlBackupServiceImp {


    @Autowired
    private MysqlBackupDao mysqlBackupDao;

    public List<String> queryTables(String tableName) {
        List<Map> listMap = mysqlBackupDao.queryTables("");
        List<String> tables = new ArrayList<>();
        listMap.forEach(ele -> {
            tables.add((String) ele.get("tableName"));
        });
        return tables;
    }

    public List<Map> queryColumns(String tableName) {
        return mysqlBackupDao.queryColumns(tableName);
    }

    public List<Map> queryData(String tableName, int start, int limit) {
        return mysqlBackupDao.queryData(tableName, start, limit);
    }

    public Integer queryCount(String tableName) {
        return mysqlBackupDao.queryCount(tableName);
    }

    public Map<String, List<String>> getTablesMap() {
        Map<String, List<String>> handleMap = new HashMap<>();
        List<String> list = queryTables("");
        list.forEach(ele -> {
            List<Map> listC = queryColumns(ele);
            List<String> colNames = new ArrayList<>();
            listC.forEach(ele2 -> {
                colNames.add((String) ele2.get("COLUMN_NAME"));
            });
            handleMap.put(ele, colNames);
        });
        return handleMap;
    }

    public void export(String path) {

        String time = DateUtils.format(new Date(), "yyyyMMddHHmmss");
        String wholePath = path + File.separator + time;
        File file = new File(wholePath);
        if (!file.exists()) {//如果文件夹不存在
            file.mkdirs();//创建文件夹
        }
        Map<String, List<String>> handleMap = getTablesMap();
        handleMap.forEach((key, value) -> {
            int count = queryCount(key);
            StringBuffer colNames = new StringBuffer();
            for (int j = 0; j < value.size(); j++) {
                if (j != 0) {
                    colNames.append(",");
                }
                colNames.append(value.get(j));
            }
            for (int i = 0; i < count; i += 10000) {
                List<Map> list = queryData(key, i, 10000);
                try {
                    for (int xx = 0; xx < list.size(); xx++) {
                        StringBuffer sb = new StringBuffer();
                        sb.append("insert into ");
                        sb.append(key + " (");
                        sb.append(colNames.toString());
                        sb.append(" ) VALUES ( ");
                        for (int hh = 0; hh < value.size(); hh++) {
                            StringBuffer sds = new StringBuffer();
                            if (hh != 0) {
                                sds.append(", ");
                            }
                            Object ob = list.get(xx).get(value.get(hh));
                            if (ob instanceof String) {
                                sds.append("'");
                                sds.append(ob);
                                sds.append("'");
                            } else if (ob instanceof Date) {
                                sds.append("'");
                                sds.append(ob);
                                sds.append("'");
                            } else {
                                sds.append(ob);
                            }
                            sb.append(sds);
                        }
                        sb.append(" ) ");


                        File f = new File(wholePath + File.separator + key);
                        RandomAccessFile randomFile = new RandomAccessFile(f, "rw");
                        // 文件长度，字节数
                        long fileLength = randomFile.length();
                        // 将写文件指针移到文件尾。
                        randomFile.seek(fileLength);
                        randomFile.write(sb.toString().getBytes());
                        randomFile.writeBytes("\n");
                        randomFile.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
